package org.redmagic.spring;

import java.util.Properties;

import org.redmagic.api.Location;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class MagicPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    private final Location location;
    private final boolean beforeOtherLocations;
    
    public MagicPropertyPlaceholderConfigurer(Location location) {
        this(location, true);
    }
    
    public MagicPropertyPlaceholderConfigurer(Location location, boolean beforeOtherLocations) {
        this.location = location;
        this.beforeOtherLocations = beforeOtherLocations;
    }
    
    @Override
    protected String resolvePlaceholder(String placeholder, Properties properties) {
        String result = null;
        if (beforeOtherLocations) {
            result = location.resolve(placeholder);
            if (result == null) {
                result = properties.getProperty(placeholder);
            }
        } else {
            result = properties.getProperty(placeholder);
            if (result == null) {
                result = location.resolve(placeholder);
            }
        }
        return result;
    }
}